package org.firstspringdema.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
public class AsyncController {
    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async-task")
    public String startAsyncTask() {
        System.out.println("主线程开始，线程名：" + Thread.currentThread().getName());

        // 调用异步方法（立即返回，不会等待方法执行完成）
        asyncService.asyncTask();

        System.out.println("主线程结束了么");
        return "异步任务已启动";
    }

    @GetMapping("/async-result")
    public String startAsyncResult() {
        System.out.println("主线程开始，线程名：" + Thread.currentThread().getName());

        // 调用带返回值的异步方法(返回CompletableFuture对象)
        CompletableFuture<String> completableFutureResult = asyncService.asyncTask2();
        System.out.println("CompletableFuture对象返回值" + completableFutureResult);

        // 可做其他操作...
        System.out.println("主线程执行其他任务");

        // 获取异步结果
        try {
            // 获取异步结果（会阻塞直到结果返回）
            String result = completableFutureResult.get(5, TimeUnit.SECONDS);
            System.out.println("主线程结束，异步结果：" + result);
            return "异步结果：" + result;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 处理中断
            return e.getMessage();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause(); // 获取任务内部异常
            return e.getMessage();
        } catch (TimeoutException e) {
            System.out.println("等待超时"+e);
            return e.getMessage();
        }
    }
}
